package com.springframework.boot.awesome.annotation.arch.util;

import com.springframework.boot.awesome.annotation.arch.exception.MonitorClassNotFoundException;
import com.springframework.boot.awesome.annotation.arch.exception.MonitorClassNotImplementException;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectUtil {

    public static Object createInstanceByPackage(String packageName) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        Class clazz = Class.forName(packageName);
        Object obj = clazz.getDeclaredConstructor().newInstance();
        return obj;
    }

    public static Method getMethod(String classPackage, String methodName, Class[] classArgs) throws MonitorClassNotImplementException, MonitorClassNotFoundException {
        Method handleFileMethod = null;
        try{
            Class clazz = Class.forName(classPackage);
            handleFileMethod = clazz.getMethod(methodName, classArgs);
        } catch (NoSuchMethodException e) {
            throw new MonitorClassNotImplementException("class not implements interface, class:" + classPackage + ", interface method: " + methodName);
        } catch (ClassNotFoundException e) {
            throw new MonitorClassNotFoundException("class package not exists: " + classPackage);
        }
        return handleFileMethod;
    }
}
